import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/assets_tool/images.dart';
import 'package:tiktokadult/hj_model/home/home_tabs_entity.dart';
import 'package:tiktokadult/hj_page/cartoon_business/acg_widget_item.dart';
import 'package:tiktokadult/hj_page/home_business/home_sub_module/home_sub_logic.dart';
import 'package:tiktokadult/hj_page/home_business/home_sub_module/widget/floating_ai_move_view.dart';
import 'package:tiktokadult/hj_page/home_business/home_sub_module/widget/sort_header.dart';
import 'package:tiktokadult/hj_page/home_business/home_sub_module/widget/special_topics_view.dart';
import 'package:tiktokadult/hj_utils/sliver_delegate.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';
import 'package:tiktokadult/tools_base/banner/ads_grid_view_widget.dart';
import 'package:tiktokadult/tools_base/loading/l_error_widget.dart';
import 'package:tiktokadult/tools_base/loading/loading_center_widget.dart';
import 'package:tiktokadult/tools_base/refresh/pull_refresh.dart';
import 'package:provider/provider.dart';

import '../../mine_business/ai/mode/ai_gril_resp.dart';
import '../../pre_sale/pre_sale_entry_widget.dart';
import '../../pre_sale/pre_sale_provider.dart';
import '../home_cell_style/video_simple_cell_widget.dart';

///  只做hj和专题切换
class HomeSubModulePage<T extends HomeSubLogic> extends StatelessWidget {
  final ModuleData module;
  final int index;

  const HomeSubModulePage(
    this.module, {
    super.key,
    required this.index,
  });

  @override
  Widget build(BuildContext context) {
    return GetBuilder<T>(
      init: instanceController<T>(module, index, false),
      global: false,
      builder: (controller) {
        return Stack(
          fit: StackFit.expand,
          children: [
            pullYsRefresh(
              onInit: (ctr) => controller.controller = ctr,
              onLoading: (refreshController) => controller.loadMoreData(),
              onRefresh: (refreshController) => controller.onRefreshData(),
              child: CustomScrollView(
                controller: controller.sctrl,
                slivers: [
                  SliverToBoxAdapter(
                    child: AdsGridViewWidget(
                      28,
                      isBigStyle: true,
                      padding: EdgeInsets.fromLTRB(10, 12, 10, 0),
                    ),
                  ),
                  //2.标签页
                  SliverToBoxAdapter(
                    child: SpecialTopicsView(
                      controller.specialTopics,
                      moudle: module,
                      padding: const EdgeInsets.fromLTRB(12, 12, 12, 3),
                    ),
                  ),
                  SliverPersistentHeader(
                    pinned: true,
                    delegate: MySliverDelegate(
                      maxHeight: 38,
                      minHeight: 38,
                      callTop: (shrinkOffset) {
                        if (shrinkOffset > 0) {
                          WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                            controller.showFAImg.value = false;
                          });
                        }
                        if (shrinkOffset <= 0) {
                          WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                            controller.showFAImg.value = true;
                          });
                        }
                      },
                      child: Container(
                        child: Obx(
                          () => HomeSortHeader(
                            tabAlignment: TabAlignment.center,
                            isInTop: controller.showFAImg.value == false,
                            labelPadding: EdgeInsets.symmetric(horizontal: 6),
                            tabs: controller.sortTitles,
                            sortCallBack: (sort) {
                              controller.sortMenuEvent(sort);
                            },
                            rightWidget: (module.type == 1) ? _buildSortStyleMenu(controller) : null,
                          ),
                        ),
                      ),
                    ),
                  ),

                  /// 展示逻辑
                  if (controller.isLoading)
                    SliverFillRemaining(
                      hasScrollBody: false,
                      child: LoadingCenterWidget(),
                    )
                  else if (controller.dataSource.isEmpty)
                    SliverFillRemaining(
                      child: CErrorWidget(retryOnTap: () => controller.onInitData()),
                    )
                  else
                    _buildList(controller),
                ],
              ),
            ),
            Positioned(
              right: 16,
              bottom: 40,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  //抽奖
                  Obx(() {
                    if (controller.showFAImg.value) {
                      return LuckyDrawButton();
                    } else {
                      return SizedBox();
                    }
                  }),
                  4.sizeBoxH,
                  //ai和预售
                  Obx(
                    () {
                      //ai女友和预售只能存在一个
                      if (controller.showFAImg.value) {
                        return Consumer<PreSaleProvider>(
                          builder: (ctx, provider, child) {
                            if (provider.presaleEnterNeedShow()) return SizedBox();
                            return Consumer<AiFloatModel>(builder: (context, model, child) {
                              if (model.visible) {
                                return Container(
                                  child: FloatingAiMoveView(
                                    closeCallBack: () {
                                      model.setVisibility(false);
                                    },
                                  ),
                                );
                              }
                              return const SizedBox();
                            });
                          },
                        );
                      } else {
                        return SizedBox();
                      }
                    },
                  ),
                  PreSaleEntryWidget(),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _buildList(HomeSubLogic controller) {
    if (controller.module.isACG)
      return SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        sliver: SliverGrid.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 111 / 196,
            mainAxisSpacing: 12,
            crossAxisSpacing: 5,
          ),
          itemCount: controller.dataSource.length,
          itemBuilder: (context, index) {
            return AcgItemWidget(info: controller.dataSource[index]);
          },
        ),
      );
    else
      return SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 4),
        sliver: SliverGrid.builder(
          itemCount: controller.dataSource.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: controller.isGridStyle.value ? 2 : 1,
            childAspectRatio: controller.isGridStyle.value ? 191 / 178 : 343 / 260,
            mainAxisSpacing: controller.isGridStyle.value ? 10 : 14,
            crossAxisSpacing: 7,
          ),
          itemBuilder: (_, index) {
            final model = controller.dataSource[index];
            return VideoSimpleCellWidget(videoModel: model);
          },
        ),
      );
  }

  Widget _buildSortStyleMenu(controller) {
    return Container(
      padding: EdgeInsets.only(right: 16),
      child: InkWell(
        onTap: controller.onTooleAction,
        child: Row(
          children: [
            Text(
              '切换',
              style: textStyle(12, Colors.white.withOpacity(.6), FontWeight.w400),
            ),
            2.sizeBoxW,
            AnimatedSwitcher(
              duration: Duration(milliseconds: 300),
              transitionBuilder: (child, anim) {
                return ScaleTransition(child: child, scale: anim);
              },
              child: Image.asset(
                controller.isGridStyle.value ? 'grid_style.png'.homePath : 'list_style.png'.homePath,
                key: ValueKey(controller.styleKey),
                width: 18,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
